<script lang="ts" setup>
import type { LowcodeDatasourceApi } from '#/api/lowcode/datasource';

import { onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { Icon } from '@iconify/vue';

import { message, Modal } from 'ant-design-vue';

import {
  deleteDatasourceConfig,
  getDatasourceConfigPage,
  testDatasourceConnection,
  updateDatasourceStatus,
  syncMagicApiDatasource,
  handleDatasourceSync,
} from '#/api/lowcode/datasource';
import { $t } from '#/locales';

import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 数据源列表和分页信息
const datasourceList = ref<LowcodeDatasourceApi.DatasourceConfig[]>([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 12,
  total: 0,
});

// 搜索表单数据
const searchForm = ref({
  name: '',
  type: '',
  status: undefined,
});

/** 刷新数据 */
async function onRefresh() {
  await loadDatasources();
}

/** 创建数据源 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 编辑数据源 */
function handleEdit(row: LowcodeDatasourceApi.DatasourceConfig) {
  formModalApi.setData(row).open();
}

/** 删除数据源 */
async function handleDelete(row: LowcodeDatasourceApi.DatasourceConfig) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    key: 'action_key_msg',
  });
  try {
    await deleteDatasourceConfig(row.id as number);
    
    // 处理删除后的同步
    const syncResult = await handleDatasourceSync('delete', row.id, autoSyncEnabled.value);
    
    message.success({
      content: syncResult.message,
      key: 'action_key_msg',
      duration: syncResult.needSync ? 8 : 3, // 需要同步时显示更长时间
    });
    
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 确认删除数据源 */
function confirmDelete(item: LowcodeDatasourceApi.DatasourceConfig) {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除数据源 "' + item.name + '" 吗？',
    onOk: () => handleDelete(item)
  });
}

// 加载数据源列表
async function loadDatasources() {
  try {
    loading.value = true;
    const result = await getDatasourceConfigPage({
      pageNo: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...searchForm.value,
    });
    
    // 处理响应数据结构
    if (result.data) {
      datasourceList.value = result.data.records || result.data.list || [];
      pagination.value.total = result.data.total || 0;
    } else {
      datasourceList.value = result.records || result.list || [];
      pagination.value.total = result.total || 0;
    }
  } catch (error) {
    message.error('加载数据源列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索数据源
function handleSearch() {
  pagination.value.current = 1;
  loadDatasources();
}

// 重置搜索
function handleReset() {
  searchForm.value = {
    name: '',
    type: '',
    status: undefined,
  };
  pagination.value.current = 1;
  loadDatasources();
}

// 分页改变
function handlePageChange(page: number, pageSize: number) {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
  loadDatasources();
}

/** 测试连接 */
async function handleTestConnection(row: LowcodeDatasourceApi.DatasourceConfig) {
  const loadingKey = `test_connection_${Date.now()}`;
  
  const hideLoading = message.loading({
    content: '正在测试连接...',
    key: loadingKey,
    duration: 0,
  });

  try {
    const result = await testDatasourceConnection(row);
    
    // 先关闭loading
    hideLoading();
    
    if (result.success) {
      message.success({
        content: `连接测试成功${result.responseTime ? ` (${result.responseTime}ms)` : ''}`,
        duration: 3,
      });
    } else {
      // 优先显示详细错误信息，然后是一般错误信息
      const errorMsg = result.errorDetails || result.message || '连接失败';
      message.error({
        content: `连接测试失败: ${errorMsg}`,
        duration: 5,
      });
    }
  } catch (error: any) {
    // 先关闭loading
    hideLoading();
    
    let errorMessage = '连接测试失败';
    
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.response?.data?.errorDetails) {
      errorMessage = error.response.data.errorDetails;
    } else if (error?.message) {
      errorMessage = error.message;
    }
    
    message.error({
      content: errorMessage,
      duration: 5,
    });
  }
}

/** 更新数据源状态 */
async function handleStatusChange(
  newStatus: number,
  row: LowcodeDatasourceApi.DatasourceConfig,
): Promise<boolean | undefined> {
  return new Promise((resolve, reject) => {
    updateDatasourceStatus(row.id as number, newStatus)
      .then(() => {
        message.success($t('ui.actionMessage.operationSuccess'));
        resolve(true);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 获取数据源类型图标
function getDatasourceIcon(type: string) {
  const iconMap: Record<string, string> = {
    'mysql': 'simple-icons:mysql',
    'postgresql': 'simple-icons:postgresql',
    'oracle': 'simple-icons:oracle',
    'sqlserver': 'simple-icons:microsoftsqlserver',
    'mongodb': 'simple-icons:mongodb',
    'redis': 'simple-icons:redis',
    'elasticsearch': 'simple-icons:elasticsearch',
  };
  return iconMap[type.toLowerCase()] || 'ant-design:database-outlined';
}

// 获取状态标签颜色
function getStatusColor(status: number) {
  return status === 1 ? 'success' : 'default';
}

// 获取状态文本
function getStatusText(status: number) {
  return status === 1 ? '启用' : '禁用';
}

/** 手动同步所有数据源到Magic API */
async function handleSyncAll() {
  Modal.confirm({
    title: '确认同步',
    content: '确定要同步所有数据源到Magic API吗？此操作会更新Magic API中的数据源配置。',
    okText: '确认同步',
    cancelText: '取消',
    onOk: async () => {
      const hideLoading = message.loading({
        content: '正在同步数据源到Magic API...',
        key: 'sync_loading',
      });
      
      try {
        const result = await syncMagicApiDatasource();
        
        message.success({
          content: `同步成功！${result.syncedCount ? `共同步 ${result.syncedCount} 个数据源` : ''}${result.failedCount ? `，${result.failedCount} 个失败` : ''}`,
          key: 'sync_loading',
          duration: 5,
        });
        
        // 如果有详细信息，显示通知
        if (result.details && result.details.length > 0) {
          console.log('同步详情:', result.details);
        }
      } catch (error: any) {
        console.error('同步失败:', error);
        message.error({
          content: `同步失败：${error?.message || '未知错误'}`,
          key: 'sync_loading',
          duration: 8,
        });
      } finally {
        hideLoading();
      }
    }
  });
}

/** 同步单个数据源到Magic API */
async function handleSyncSingle(dataSource: LowcodeDatasourceApi.DatasourceConfig) {
  if (dataSource.status !== 1) {
    message.warning(`数据源"${dataSource.name}"未启用，无法同步到Magic API`);
    return;
  }
  
  const hideLoading = message.loading({
    content: `正在同步数据源"${dataSource.name}"到Magic API...`,
    key: 'sync_single_loading',
  });
  
  try {
    const result = await syncMagicApiDatasource(dataSource.id);
    
    message.success({
      content: `数据源"${dataSource.name}"同步成功！`,
      key: 'sync_single_loading',
      duration: 3,
    });
    
    // 如果有详细信息，记录到控制台
    if (result.details && result.details.length > 0) {
      console.log(`数据源 ${dataSource.name} 同步详情:`, result.details);
    }
  } catch (error: any) {
    console.error('同步失败:', error);
    
    // 提供更详细的错误信息
    let errorMessage = `同步失败：${error?.message || '未知错误'}`;
    if (error?.response?.status === 404) {
      errorMessage = '同步失败：Magic API服务未找到，请检查服务是否启动';
    } else if (error?.response?.status >= 500) {
      errorMessage = '同步失败：服务器内部错误，请稍后重试或联系管理员';
    }
    
    message.error({
      content: errorMessage,
      key: 'sync_single_loading',
      duration: 8,
    });
  } finally {
    hideLoading();
  }
}

// 自动同步选项
const autoSyncEnabled = ref(false);

// 从localStorage恢复自动同步设置
function loadAutoSyncSetting() {
  const saved = localStorage.getItem('datasource-auto-sync');
  autoSyncEnabled.value = saved === 'true';
}

// 保存自动同步设置
function saveAutoSyncSetting(enabled: boolean) {
  localStorage.setItem('datasource-auto-sync', enabled.toString());
  autoSyncEnabled.value = enabled;
}

onMounted(() => {
  loadDatasources();
  loadAutoSyncSetting();
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    
    <div class="datasource-container">
      <!-- 顶部工具栏卡片 -->
      <a-card class="header-card" size="small">
        <div class="toolbar">
          <div class="toolbar-left">
            <h3 class="page-title">数据源管理</h3>
          </div>
          <div class="toolbar-right">
            <!-- 同步到Magic API按钮 -->
            <a-button 
              type="primary" 
              ghost
              @click="handleSyncAll"
              title="同步所有数据源到Magic API"
            >
              <template #icon>
                <Icon icon="ant-design:sync-outlined" />
              </template>
              同步到Magic API
            </a-button>
            
            <!-- 新增数据源按钮 -->
            <a-button 
              type="primary" 
              @click="handleCreate"
            >
              <template #icon>
                <Icon icon="ant-design:plus-outlined" />
              </template>
              新增数据源
            </a-button>
            
            <!-- 刷新按钮 -->
            <a-button @click="onRefresh" :loading="loading">
              <template #icon>
                <Icon icon="ant-design:reload-outlined" />
              </template>
              刷新
            </a-button>
          </div>
        </div>
      </a-card>

      <!-- 搜索表单 -->
      <a-card class="search-card" size="small">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="数据源名称">
            <a-input 
              v-model:value="searchForm.name" 
              placeholder="请输入数据源名称"
              style="width: 200px"
              @press-enter="handleSearch"
            />
          </a-form-item>
          <a-form-item label="数据源类型">
            <a-select 
              v-model:value="searchForm.type" 
              placeholder="请选择数据源类型"
              style="width: 150px"
              allowClear
            >
              <a-select-option value="mysql">MySQL</a-select-option>
              <a-select-option value="postgresql">PostgreSQL</a-select-option>
              <a-select-option value="oracle">Oracle</a-select-option>
              <a-select-option value="sqlserver">SQL Server</a-select-option>
              <a-select-option value="mongodb">MongoDB</a-select-option>
              <a-select-option value="redis">Redis</a-select-option>
              <a-select-option value="elasticsearch">Elasticsearch</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select 
              v-model:value="searchForm.status" 
              placeholder="请选择状态"
              style="width: 100px"
              allowClear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon>
                  <Icon icon="ant-design:search-outlined" />
                </template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon>
                  <Icon icon="ant-design:reload-outlined" />
                </template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
          
          <!-- 自动同步开关 -->
          <a-form-item>
            <a-tooltip title="启用后，数据源修改时将自动同步到Magic API">
              <a-switch 
                v-model:checked="autoSyncEnabled"
                @change="saveAutoSyncSetting"
                size="small"
              />
              <span class="ml-2 text-sm text-gray-600">自动同步Magic API</span>
            </a-tooltip>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 数据源卡片列表 -->
      <a-spin :spinning="loading">
        <div v-if="datasourceList.length === 0 && !loading" class="empty-state">
          <a-empty description="暂无数据源配置">
            <a-button type="primary" @click="handleCreate">
              立即创建
            </a-button>
          </a-empty>
        </div>
        <div v-else class="card-grid">
          <a-card
            v-for="item in datasourceList"
            :key="item.id"
            class="datasource-card"
            hoverable
          >
            <!-- 卡片头部 -->
            <template #title>
              <div class="card-header">
                <div class="card-icon">
                  <Icon :icon="getDatasourceIcon(item.type)" size="24" />
                </div>
                <div class="card-title-info">
                  <div class="card-name">{{ item.name }}</div>
                  <div class="card-type">{{ item.type?.toUpperCase() }}</div>
                </div>
              </div>
            </template>
            
            <!-- 卡片操作按钮 -->
            <template #extra>
              <a-dropdown :trigger="['click']" placement="bottomRight">
                <a-button type="text" size="small">
                  <Icon icon="ant-design:more-outlined" />
                </a-button>
                <template #overlay>
                  <a-menu class="datasource-menu">
                    <a-menu-item key="edit" @click="handleEdit(item)">
                      <div class="menu-item-content">
                        <Icon icon="ant-design:edit-outlined" />
                        <span>编辑</span>
                      </div>
                    </a-menu-item>
                    <a-menu-item key="test" @click="handleTestConnection(item)">
                      <div class="menu-item-content">
                        <Icon icon="ant-design:link-outlined" />
                        <span>测试连接</span>
                      </div>
                    </a-menu-item>
                    <a-menu-item key="sync" @click="handleSyncSingle(item)">
                      <div class="menu-item-content">
                        <Icon icon="ant-design:sync-outlined" />
                        <span>同步到Magic API</span>
                      </div>
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="delete" @click="() => confirmDelete(item)">
                      <div class="menu-item-content">
                        <Icon icon="ant-design:delete-outlined" />
                        <span>删除</span>
                      </div>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>

            <!-- 卡片内容 -->
            <div class="card-content">
              <div class="card-info">
                <div class="info-row">
                  <span class="info-label">数据库:</span>
                  <span class="info-value">{{ item.database || '-' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">用户名:</span>
                  <span class="info-value">{{ item.username || '-' }}</span>
                </div>
                <div class="info-row" v-if="item.description">
                  <span class="info-label">描述:</span>
                  <span class="info-value">{{ item.description }}</span>
                </div>
              </div>
              
              <!-- 状态信息和操作 -->
              <div class="card-status">
                <div class="status-left">
                  <a-tag :color="getStatusColor(item.status)">
                    {{ getStatusText(item.status) }}
                  </a-tag>
                  <span class="create-time">
                    {{ new Date(item.createTime).toLocaleDateString() }}
                  </span>
                </div>
                <div class="status-actions">
                  <a-tooltip title="测试连接">
                    <Icon 
                      icon="ant-design:thunderbolt-outlined" 
                      @click="handleTestConnection(item)"
                      class="action-icon test-icon"
                    />
                  </a-tooltip>
                  <a-tooltip :title="item.status === 1 ? '点击禁用' : '点击启用'">
                    <a-switch
                      :checked="item.status === 1"
                      size="small"
                      @change="(checked) => handleStatusChange(checked ? 1 : 0, item)"
                    />
                  </a-tooltip>
                </div>
              </div>
            </div>
          </a-card>
        </div>
      </a-spin>

      <!-- 分页 -->
      <div class="pagination-container" v-if="datasourceList.length > 0">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
          @change="handlePageChange"
          @show-size-change="handlePageChange"
        />
      </div>
    </div>
  </Page>
</template>

<style scoped>
.datasource-container {
  padding: 0;
}

.header-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left .page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.datasource-card {
  height: 200px;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.datasource-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.card-title-info {
  flex: 1;
  min-width: 0;
}

.card-name {
  font-size: 15px;
  font-weight: 600;
  color: #262626;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-type {
  font-size: 11px;
  color: #8c8c8c;
  text-transform: uppercase;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.card-content {
  height: auto;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.card-info {
  flex: 1;
  padding-bottom: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
  align-items: flex-start;
}

.info-label {
  width: 60px;
  color: #8c8c8c;
  font-size: 12px;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  color: #595959;
  font-size: 12px;
  word-break: break-all;
  line-height: 1.3;
}

.card-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.create-time {
  font-size: 11px;
  color: #999;
  white-space: nowrap;
}

.status-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-icon {
  cursor: pointer;
  font-size: 16px;
  color: #1890ff;
  transition: color 0.3s ease;
}

.action-icon:hover {
  color: #40a9ff;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-grid {
    grid-template-columns: 1fr;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-right {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .datasource-card {
    height: auto;
    min-height: 200px;
  }
}

/* 下拉菜单样式 */
.datasource-menu {
  min-width: 120px;
}

.menu-item-content {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.menu-item-content span {
  line-height: 1;
}

</style>